<?php

namespace App\Http\Controllers\Api\V2;

use App\Models\XoUser;
use App\Models\UserCoupon;
use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Jobs\SendXoRegisterEmail;
use App\Jobs\SendXoForgotPassword;
use App\Transformers\XoUserTransformer;

use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;

class UserController extends BaseController
{
    /**
     * @api {get} /users 用户列表(user list)
     * @apiDescription 用户列表(user list)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "data": [
     *         {
     *           "id": 2,
     *           "email": "490554191@qq.com",
     *           "name": "fff",
     *           "created_at": "2015-11-12 10:37:14",
     *           "updated_at": "2015-11-13 02:26:36",
     *           "deleted_at": null
     *         }
     *       ],
     *       "meta": {
     *         "pagination": {
     *           "total": 1,
     *           "count": 1,
     *           "per_page": 15,
     *           "current_page": 1,
     *           "total_pages": 1,
     *           "links": []
     *         }
     *       }
     *     }
     */
    public function index(XoUser $user)
    {
        $users = XoUser::paginate();

        return $this->response->paginator($users, new XoUserTransformer());
    }

    /**
     * @api {put} /user/password 修改密码(edit password)
     * @apiDescription 修改密码(edit password)
     * @apiGroup user
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiParam {String} old_password          旧密码
     * @apiParam {String} password              新密码
     * @apiParam {String} password_confirmation 确认新密码
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 204 No Content
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 400 Bad Request
     *     {
     *         "password": [
     *             "两次输入的密码不一致",
     *             "新旧密码不能相同"
     *         ],
     *         "password_confirmation": [
     *             "两次输入的密码不一致"
     *         ],
     *         "old_password": [
     *             "密码错误"
     *         ]
     *     }
     */
    public function editPassword(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'old_password' => 'required',
            'password' => 'required|confirmed|different:old_password',
            'password_confirmation' => 'required|same:password',
        ]);

        if ($validator->fails()) {
            // return $this->errorBadRequest($validator);
            return $this->returnError($validator);
        }

        $user = $this->user();

        $auth = \Auth::once([
            'email' => $user->email,
            'password' => $request->get('old_password'),
        ]);

        if (! $auth) {
            // return $this->response->errorUnauthorized();
            return $this->returnFail('旧密码有误');
        }

        $password = app('hash')->make($request->get('password'));
        $user->update(['password' => $password]);

        return $this->returnSuccess([], '更新成功');

        // return $this->response->noContent();
    }

    /**
     * @api {get} /users/{id} 某个用户信息(some user's info)
     * @apiDescription 某个用户信息(some user's info)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "data": {
     *         "id": 2,
     *         "email": "490554191@qq.com",
     *         "name": "fff",
     *         "created_at": "2015-11-12 10:37:14",
     *         "updated_at": "2015-11-13 02:26:36",
     *         "deleted_at": null
     *       }
     *     }
     */
    public function show($id)
    {
        $user = XoUser::findOrFail($id);

        return $this->response->item($user, new XoUserTransformer());
    }

    /**
     * @api {get} /user 当前用户信息(current user info)
     * @apiDescription 当前用户信息(current user info)
     * @apiGroup user
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "data": {
     *         "id": 2,
     *         "email": 'liyu01989@gmail.com',
     *         "name": "foobar",
     *         "created_at": "2015-09-08 09:13:57",
     *         "updated_at": "2015-09-08 09:13:57",
     *         "deleted_at": null
     *       }
     *     }
     */
    public function userShow()
    {
		$user = $this->user();
        // $item = $this->response->item($user, new UserTransformer());
		$data = $user->attributesToArray();
		\Log::info('user data: '.var_export($data, true));
		//添加上其它信息
		return $this->returnSuccess($data);
    }

    /**
     * @api {post} /user/update 修改个人信息(update my info)
     * @apiDescription 修改个人信息(update my info)
     * @apiGroup user
     * @apiPermission JWT
     * @apiVersion 0.1.0
     * @apiParam {String} [name] name
     * @apiParam {Url} [avatar] avatar
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *        "id": 2,
     *        "email": 'liyu01989@gmail.com',
     *        "name": "ffff",
     *        "created_at": "2015-10-28 07:30:56",
     *        "updated_at": "2015-10-28 09:42:43",
     *        "deleted_at": null,
     *     }
     */
    public function update(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'name' => 'string|max:50',
            'phone' => 'required|phone',
        ]);
		
        if ($validator->fails()) {
            return $this->returnError($validator);
        }
		$user = $this->user();
		$phone = $request->get('phone');
		$email = $request->get('email');
		$exits1 = XoUser::where('phone', $phone)->where('id', '!=', $user->id)->first();
		
		if($exits1){
			return $this->returnFail('手机号已被注册');
		}
		if($email){
			$exits2 = XoUser::where('email', $email)->where('id', '!=', $user->id)->first();
			if($exits2){
				return $this->returnFail('邮箱已被注册');
			}
		}
		
        $attributes = array_filter($request->only('name', 'phone', 'email', 'sex'));
		\Log::info(\var_export($attributes, true));
		$attributes['sex'] = $request->get('sex');
		$ret = false;
        if ($attributes) {
            $ret = $user->update($attributes);
        }

        return $this->returnSuccess($ret, '更新成功');
    }

    /**
	 * http://api.cut.com/api/users?email=fengwch_sir@yeah.net&name=fengwch_sir&password=123456
     * @api {post} /users 创建一个用户(create a user)
     * @apiDescription 创建一个用户(create a user)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {Email}  email   email[unique]
     * @apiParam {String} password   password
     * @apiParam {String} name      name
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *         token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY
     *     }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 400 Bad Request
     *     {
     *         "email": [
     *             "该邮箱已被他人注册"
     *         ],
     *     }
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'email' => 'required|email|unique:xo_users',
            'name' => 'required|string',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            // return $this->errorBadRequest($validator);
            return $this->returnError($validator);
        }

        $email = $request->get('email');
        $password = $request->get('password');
        $name = $request->get('name');

        $attributes = [
            'email' => $email,
            'name' => $name,
            'password' => app('hash')->make($password),
        ];
        
        $user = XoUser::create($attributes);
        
        // 用户注册成功后发送邮件
        dispatch(new SendXoRegisterEmail($user, $password));

        if(! $token = \Auth::guard('api')->attempt(['email' => $email, 'password' => $password])){
			return $this->returnFail(trans('auth.auth_token_empty'));
		}

		$authorization = new Authorization($token);
		$authInfo = $authorization->toArray();
		// $userInfo =  $this->response->item($user, new UserTransformer());
		//{"code":0,"msg":"success","data":{"exception":null,"headers":{},"original":{"name":"15217331661","phone":"15217331661","updated_at":"2020-08-11 07:54:33","created_at":"2020-08-11 07:54:33","id":1}}}
		$userInfo = $user->attributesToArray();
		$userInfo['auth_info'] = $authInfo;
		return $this->returnSuccess($userInfo);

        // 201 with location
        // $location = dingo_route('v2', 'users.show', $user->id);

        // return $this->response->item($user, new XoUserTransformer())
        //     ->header('Location', $location)
        //     ->setStatusCode(201);
    }
	
	
	/**
	 * http://api.cut.com/api/register?phone=15217331661&code=
	 * @api {post} /register 注册一个用户(create a user)
	 * @apiDescription 注册一个用户(create a user)
	 * @apiGroup user
	 * @apiPermission none
	 * @apiVersion 0.1.0
	 * @apiParam {Phone}  phone   phone[unique]
	 * @apiErrorExample {json} Error-Response:
	 *     HTTP/1.1 400 Bad Request
	 *     {
	 *         "email": [
	 *             "手机已被使用"
	 *         ],
	 *     }
	 */
	public function register(Request $request)
	{
	    $validator = \Validator::make($request->input(), [
	        'phone' => 'required|phone|unique:xo_users',
	        'code' => 'required|string',
	    ]);
	
	    if ($validator->fails()) {
            return $this->returnError($validator);
	    }
	
	    $code = $request->get('code');
	    $phone = $request->get('phone');
		
		//check code 
		$value = Cache::get('phone_captcha_'.$phone);
		$value = 1234;
		if(empty($value)){
			return $this->returnFail(trans('auth.captcha_retry_again'));
		}
		if($value != $code){
			return $this->returnFail(trans('auth.captcha_noeq'));
		}
		$password = '123456';
	    $attributes = [
			'name' => $phone,
	        'phone' => $phone,
			'password' => $password,
	    ];
	    $user = XoUser::create($attributes);
	
	    // 201 with location
	    // $location = dingo_route('v1', 'users.show', $user->id);
	
		// {"data":{"id":1,"email":null,"name":"15217331661","headimg":null,"created_at":"2020-08-10 08:45:03","updated_at":"2020-08-10 08:45:03"}}
	    // return $this->response->item($user, new UserTransformer())
	    //     ->header('Location', $location)
	    //     ->setStatusCode(201);
		if(! $token = \Auth::guard('api')->attempt(['phone' => $phone, 'password' => $password])){
			return $this->returnFail(trans('auth.auth_token_empty'));
		}
		
		$authorization = new Authorization($token);
		$authInfo = $authorization->toArray();
		// $userInfo =  $this->response->item($user, new UserTransformer());
		//{"code":0,"msg":"success","data":{"exception":null,"headers":{},"original":{"name":"15217331661","phone":"15217331661","updated_at":"2020-08-11 07:54:33","created_at":"2020-08-11 07:54:33","id":1}}}
		$userInfo = $user->attributesToArray();
		$userInfo['auth_info'] = $authInfo;
		return $this->returnSuccess($userInfo);
	}
	
	/**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    // public function authenticate(Request $request)
    // {
    //     $credentials = $request->only('email', 'password');

    //     if (Auth::attempt($credentials)) {
    //         // 通过认证..
    //         return redirect()->intended('dashboard');
    //     }
    // }

    /**
     * 忘记密码 邮箱发送确认链接
     *
     * @param Request $request
     * @return void
     */
    public function forgot(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return $this->returnError($validator);
        }

        $email = $request->get('email');
        
        $existUser = XoUser::where('email', $email)->where('email', $email)->first();
        if(!$existUser){
            return $this->returnFail(trans('auth.nocorrect_user'));
        }
        // 用户注册成功后发送邮件
        dispatch(new SendXoForgotPassword($email, $existUser['id']));

		return $this->returnSuccess([]);
    }

    /**
     * 确认修改密码
     *
     * @param Request $request
     * @return void
     */
    public function confirm_reset(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'id' => 'required',
            'i' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError($validator);
        }

        $id = $request->get('id');
        $i = $request->get('i');

        $password = Crypt::decrypt(base64_decode($i));
        \Log::debug('confirm_reset id '.$id.' password: '.$password);

        $attributes = [
            'password' => app('hash')->make($password),
        ];
        $ret = XoUser::where('id', $id)->update($attributes);
        if(!$ret){
            return 'fail';
        }
        $url = env('PASSWORD_RESET_LOC');
        return redirect($url);
        // return Redirect::to($url);
    }
}
